<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

    public $tab = '';
    public $sub = '';

    public function __construct() {
        parent::__construct();
    }

    function init_account($user_id) {
        $this->load->model('Account_model', 'account');
        $account = $this->account->get_account($user_id);
        if (!$account) {
            $initAccount = array(
                'user_id' => $user_id,
                'total' => '0',
                'use_money' => '0',
                'no_use_money' => '0',
                'collection' => '0',
            );
            $this->account->init_account($initAccount);
        }
    }

    public function get_user_info($user_tab, $user_sub, $sub = '') {
        $user = $this->session->userdata('zjy_user');
        $this->load->model('User_model', 'user');
        $data['user'] = $this->user->get_by_uid($user['user_id']);

        $this->load->model('User_vip_model', 'user_vip');
        $data['user_vip'] = $this->user_vip->get_by_uid($user['user_id']);

        $this->init_account($user['user_id']);

        $data['tab'] = $this->tab;
        $data['sub'] = $sub ? $sub : $this->sub;
        $data['user_tab'] = $user_tab;
        $data['user_sub'] = $user_sub;

        return $data;
    }

    function sendsms($phone, $msg) {
        $this->load->library('phone');
        $res = $this->phone->send($phone, $msg);
        $status = explode(':',$res);//处理返回值
        if($status[0] != "success") {
            $res = '';
        }
        return $res;
    }

    function letterStation($uid, $name, $content) {
        $this->load->model('Message_model', 'message');
        $msg = array(
            'sent_user' => 1,
            'receive_user' => $uid,
            'name' => $name,
            'fstatus' => 0,
            'message_type' => '1',
            'sented' => 0,
            'deltype' => 0,
            'content' => $content,
            'add_time' => time(),
            'addip' => $this->input->ip_address()
        );
        $this->message->send($msg);
    }

    function Credit($user_id, $nid, $op = 1) {
        $this->load->model('Credit_model', 'credit');
        $credit_info = $this->credit->get_credit_rule(array('nid' => $nid));
        $creditlog = array(
            'user_id' => $user_id,
            'type_id' => $credit_info['id'],
            'op' => 1, //变动类型,1:增加,2:减少
            'credit_value' => $credit_info['credit_value'],
            'remark' => $credit_info['name'] . $op > 1 ? '扣除积分' : '送积分',
            'op_user' => 1,
            'add_time' => time(),
            'addip' => $this->input->ip_address()
        );
        $this->credit->incr_credit($creditlog);
    }

    function notice_doc_credit($user_id, $jifen, $name) {
        $this->load->model('Credit_model', 'credit');
        $credit_info = $this->credit->get_credit_rule(array('nid' => 'zhengjian'));
        $log = array(
            'user_id' => $user_id,
            'type_id' => $credit_info['id'],
            'op' => 1,
            'credit_value' => $jifen,
            'remark' => $name . '送积分',
            'op_user' => 1,
            'add_time' => time(),
            'addip' => $this->input->ip_address()
        );
        $this->credit->incr_credit($log);
    }

    function Notice($type, $uid, $data = array()) {

        $emailTxt = filePath('config/emailtxt');
        $smsTxt = filePath("config/smstxt");
        $emailTxt = de_xie($emailTxt);
        $smsTxt = de_xie($smsTxt);

        $this->load->library('func');
        $this->load->model('User_model', 'user');
        if ($uid > 0) {
            $minfo = $this->user->get_by_uid($uid);
            $username = $minfo['username'];
            $user_id = $minfo['user_id'];
            $webname = CON_PLATFORMNAME;
            $email = $minfo['email'];
            $str = implode(',',array($user_id,$username,$email));

            $this->load->library('/phpmailer/PHPMailer');
            $this->phpmailer->IsSMTP();
            $this->phpmailer->IsHTML(FALSE);
            $this->phpmailer->AddAddress($email, $username); //收件人
        }




        switch ($type) {
            case 1://注册成功发送邮件
                $active_id = urlencode($this->func->authcode($str, "ENCODE"));

                $weburl = "http://{$_SERVER['HTTP_HOST']}/reg/activation?act={$active_id}";
                $link = '<a href="' . $weburl . '" style="color:#91273d">点击链接验证邮件</a>';

                /* 站内信 */
                //$body = str_replace(array("#UserName#"),array($username),$msgTxt['regsuccess']);
                //addInnerMsg($uid,"恭喜您注册成功",$body);
                /* 站内信 */

                /* 邮件 */
                $subject = "您刚刚在" . $webname . "注册成功";
                $msgBody = str_replace(array("#UserName#", "#LINK#", "#PWEBURL#"), array($username, $link, $weburl), $emailTxt['regsuccess']);
                $this->phpmailer->Subject = $subject;
                $this->phpmailer->Body = $msgBody;
                $send = $this->phpmailer->Send();
                return $send;
                break;

            case 2://登陆密码找回发邮件
                $str = implode(',', array(time(), $user_id, $username, $email));
                $pactive_id = urlencode($this->func->authcode($str, "ENCODE", '', 3600));
                $pweburl = "http://{$_SERVER['HTTP_HOST']}/password/getpwd?check=" . $pactive_id;
                $plink = '<a href="' . $pweburl . '" style="color:#91273d">点击链接找回密码</a>';
                /* 邮件 */

                $subject = CON_PLATFORMNAME . "登陆密码找回";
                $msgBody = str_replace(array("#UserName#", "#PWDLINK#", "#PWEBURL#"), array($username, $plink, $pweburl), $emailTxt['findPwdMail']);
                $this->phpmailer->Subject = $subject;
                $this->phpmailer->Body = $msgBody;
                $send = $this->phpmailer->Send();
                return $send;
                break;

            case 3://交易密码找回发邮件
                $payactive_id = urlencode($this->func->authcode($str . ',' . time(), "ENCODE", '', 3600));
                $payweburl = "http://{$_SERVER['HTTP_HOST']}/password/paypwd?check=" . $payactive_id;
                $paylink = '<a href="' . $payweburl . '" style="color:#91273d">点击链接找回交易密码</a>';

                /* 邮件 */
                $subject = CON_PLATFORMNAME . "交易密码找回";
                $msgBody = str_replace(array("#UserName#", "#PAYLINK#", "#PWEBURL#"), array($username, $paylink, $payweburl), $emailTxt['findPaypwdMail']);
                $this->phpmailer->Subject = $subject;
                $this->phpmailer->Body = $msgBody;
                $send = $this->phpmailer->Send();
                return $send;
                break;
            case 4://手机认证发送验证码：
                $vcode = $data['vcode'];
                $content = str_replace(array("#CODE#"), array($vcode), $smsTxt['verify_phone']);
                $send = $this->sendsms($data['phone'], $content);
                return $send;
                break;
            case 5://线上充值成功
                $vmoney = $data['money'];
                $content = str_replace(array("#MONEY#"), array($vmoney), $smsTxt['payonline']);
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;

            case 6://还款到账
//                $borrow_id = $data['borrow_id'];
//                $borrow_order = $data['forder'];
//                $content = str_replace(array("#ID#", "#ORDER#"), array($borrow_id, $borrow_order), $smsTxt['payback']);
                $borrow_title = $data['borrow_title'];
                $use_money = $data['use_money'];
                $content = str_replace(array("#TITLE#", "#USE_MONEY#"), array($borrow_title, $use_money), $smsTxt['payback']);
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 7://提现成功
                $vdate = $data['vdate'];
                $vmoney = $data['vmoney'];
                $vcredit = $data['vcredit'];
                $vfee = $data['vfee'];
                $content = str_replace(array("#DATE#", "#WITHDRAWMONEY#", "CREDITED", "FEE"), array($vdate, $vmoney, $vcredit, $vfee), $smsTxt['withdraw']);
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 8://VIP认证通过
                $content = $smsTxt['vip'];
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 9://发标初审通过
                $content = $smsTxt['firstV'];
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 10://发标复审通过
                $content = $smsTxt['approve'];
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 11://手机认证发送验证码：
                $vcode = $data['vcode'];
                $content = str_replace(array("#CODE#"), array($vcode), $smsTxt['verify_phone']);
                $send = $this->sendsms($minfo['phone'], $content);
                return $send;
                break;
            case 12://登录密码找回手机验证码：
                $vcode = $data['vcode'];
                $content = str_replace(array("#CODE#"), array($vcode), $smsTxt['login_password']);
                $send = $this->sendsms($data['phone'], $content);
                return $send;
                break;
        }
    }

    /**
     *
        $mmmconfig[] = array(
            'fromUserId' => '', //付款人userId
            'fromMmm' => '', //付款人乾多多标识
            'toUserId' => '', //收款人userId
            'toMmm' => '', //收款人乾多多标识
            'batchNo' => '', //网贷平台标号
            'amount' => 0, //转账金额
            'fullAmount' => 0, //总转账金额
            'transferName' => '', //用途
            'remark' => '', //备注
            'secondary' => array(), //二次分配列表
        );
        $secondary[] = array(
            'toMmm' => '', //二次收款人乾多多标识
            'amount' => 0, //二次分配金额
            'transferName' => '', //二次分配用途
            'remark' => '', //备注
        );
     *
     * @param type $mmmconfig   双乾转账配置信息，事例见上
     * @param type $mmmType     转款标示
     * @param type $flagStr     会通过remark2原数返回
     * @param type $TransferAction  转账类型  1.投标  2.还款  3.其他
     * @param type $Action      操作类型  1.手动转账  2.自动转账
     */
    public function noticeMmm($mmmconfig, $mmmType, $flagStr = '', $TransferAction = '3', $Action = '1', $NeedAudit = '1') {
        if (!is_array($mmmconfig)) {
            exit('支付信息错误');
        }
        if (empty($mmmType)){
            exit('请提供转账类型');
        }

        $this->load->library('/mmm/Rsa', 'rsa');
        $this->load->library('/mmm/Common', 'common');
        $this->load->library('/mmm/LoanInfoBean', 'loaninfobean');
        $this->load->library('/mmm/LoanInfoSecondaryBean', 'loaninfosecondarybean');

        $loanList = array();
        foreach ($mmmconfig as $conf) {
            //组织二次分配
            $secondaryJsonList = '';
            if (isset($conf['secondary'])) {
                $secondaryData = $conf['secondary'];
                $arrsecondary = array();
                foreach ($secondaryData as $second) {
                    if ($second['amount'] <= 0) {
                        continue;
                    }
                    $mmtoId = empty($second['toMmm']) ? MONEYMOREMOREPID : $second['toMmm'];
                    $secondary = new LoanInfoSecondaryBean($mmtoId, $second['amount'], $second['transferName'], $second['remark']);
                    $arrsecondary[] = array(
                        "LoanInMoneymoremore"   => $secondary->LoanInMoneymoremore,
                        "Amount"                => $secondary->Amount,
                        "TransferName"          => $secondary->TransferName,
                        "Remark"                => $secondary->Remark
                    );
                }

                $secondaryJsonList= json_encode($arrsecondary);
            }

            $arr = array();
            //订单号
            $invNo = $conf['fromUserId'] . '#' . $conf['toUserId'] . '#' . $conf['fromMmm'] . '#' . $conf['toMmm'] . '#' . date('YmdHis');
            $loaninfo = new LoanInfoBean($conf['fromMmm'], $conf['toMmm'], $invNo, $conf['batchNo'], '', '', $conf['amount'], $conf['fullAmount'], $conf['transferName'], '', $secondaryJsonList);
            $arr['LoanOutMoneymoremore'] = $loaninfo->LoanOutMoneymoremore;
            $arr['LoanInMoneymoremore'] = $loaninfo->LoanInMoneymoremore;
            $arr['OrderNo'] = $loaninfo->OrderNo;
            $arr['BatchNo'] = $loaninfo->BatchNo;
            $arr['ExchangeBatchNo'] = $loaninfo->ExchangeBatchNo;
            $arr['AdvanceBatchNo'] = $loaninfo->AdvanceBatchNo;
            $arr['Amount'] = $loaninfo->Amount;
            $arr['FullAmount'] = $loaninfo->FullAmount;
            $arr['TransferName'] = $loaninfo->TransferName;
            $arr['Remark'] = $loaninfo->Remark;
            $arr['SecondaryJsonList'] = $loaninfo->SecondaryJsonList;
            $loanList[] = $arr;
        }

        $LoanJsonList = json_encode($loanList); //参数

        $PlatformMoneymoremore = MONEYMOREMOREPID;   //平台标示
        //$TransferAction = '1';    //转账类型  1.投标  2.还款  3.其他
        //$Action = '1';    //操作类型  1.手动转账  2.自动转账
        $TransferType = '2';    //转账方式  1.桥连   2.直连
        //$NeedAudit = '';    //通过是否需要审核   空.需要审核   1.自动通过
        if ($this->common->getAntiState() == 0) {
            $RandomTimeStamp = "";
        } else if ($this->common->getAntiState() == 1) {
            $RandomTimeStamp = $this->common->getRandomTimeStamp();
        }
        $ReturnURL = "http://" . $_SERVER["HTTP_HOST"] . "/moneymoremore/mmmReturn.html";
        $NotifyURL = "http://" . $_SERVER["HTTP_HOST"] . "/moneymoremore/mmmNotify.html";


        $Remark1 = $mmmType;
        $Remark2 = $flagStr;
        $Remark3 = "";


        $dataStr = $LoanJsonList . $PlatformMoneymoremore . $TransferAction . $Action . $TransferType . $NeedAudit . $RandomTimeStamp . $Remark1 . $Remark2 . $Remark3 . $ReturnURL . $NotifyURL;
        if ($this->common->getAntiState() == 1) {
            $dataStr = strtoupper(md5($dataStr));
        }
        $SignInfo = $this->rsa->sign($dataStr);

        $LoanJsonList = urlencode($LoanJsonList);

        $officialAction = MONEYMOREMOREURL . "/loan/loan.action";

        echo "<form id=\"formu\" name=\"formu\" action=\"" . $officialAction . "\" method=\"post\">";
        echo "<input id=\"LoanJsonList\" name=\"LoanJsonList\" value=\"" . $LoanJsonList . "\" type=\"hidden\" />";
        echo "<input id=\"PlatformMoneymoremore\" name=\"PlatformMoneymoremore\" value=\"" . $PlatformMoneymoremore . "\" type=\"hidden\" />";
        echo "<input id=\"TransferAction\" name=\"TransferAction\" value=\"" . $TransferAction . "\" type=\"hidden\" />";
        echo "<input id=\"Action\" name=\"Action\" value=\"" . $Action . "\" type=\"hidden\" />";
        echo "<input id=\"TransferType\" name=\"TransferType\" value=\"" . $TransferType . "\" type=\"hidden\" />";
        echo "<input id=\"NeedAudit\" name=\"NeedAudit\" value=\"" . $NeedAudit . "\" type=\"hidden\" />";
        echo "<input id=\"RandomTimeStamp\" name=\"RandomTimeStamp\" value=\"" . $RandomTimeStamp . "\" type=\"hidden\" />";
        echo "<input id=\"Remark1\" name=\"Remark1\" value=\"" . $Remark1 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark2\" name=\"Remark2\" value=\"" . $Remark2 . "\" type=\"hidden\" />";
        echo "<input id=\"Remark3\" name=\"Remark3\" value=\"" . $Remark3 . "\" type=\"hidden\" />";
        echo "<input id=\"ReturnURL\" name=\"ReturnURL\" value=\"" . $ReturnURL . "\" type=\"hidden\" />";
        echo "<input id=\"NotifyURL\" name=\"NotifyURL\" value=\"" . $NotifyURL . "\" type=\"hidden\" />";
        echo "<input id=\"SignInfo\" name=\"SignInfo\" value=\"" . $SignInfo . "\" type=\"hidden\" />";
        echo "<script language=\"javascript\">window.onload=function(){document.formu.submit();}</script>";
        echo "</form>";
    }

}
